package com.javaDemo.ti;

/**
 * @ClassName: Hebingkgelianbiao
 * @Auther: csy https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/leetcode-23-he-bing-kge-pai-xu-lian-biao-by-powcai/
 * @Date: 2021/3/12 00:50
 * @Description: 分治思想
 */
public class Hebingkgelianbiao {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        ListNode l1=new ListNode(1);
        l1.next=new ListNode(3);
        l1.next.next=new ListNode(4);
        ListNode l2=new ListNode(2);
        l2.next=new ListNode(5);
        l2.next.next=new ListNode(6);
        ListNode l3=new ListNode(4);
        l3.next=new ListNode(6);
        l3.next.next=new ListNode(7);
        ListNode[] lists= {l1,l2,l3};
        System.out.println(mergeKLists(lists));
    }


    public static ListNode mergeKLists(ListNode[] lists) {
            if (lists == null || lists.length == 0) return null;
            return merge(lists, 0, lists.length - 1);
        }

        private static ListNode merge(ListNode[] lists, int left, int right) {
            if (left == right) {
                return lists[left];
            }
            int mid = left + (right - left) / 2;
            ListNode l1 = merge(lists, left, mid);
            ListNode l2 = merge(lists, mid + 1, right);
            return mergeTwoLists(l1, l2);
        }

        private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null) return l2;
            if (l2 == null) return l1;
            if (l1.val < l2.val) {
                l1.next = mergeTwoLists(l1.next, l2);
                return l1;
            } else {
                l2.next = mergeTwoLists(l1, l2.next);
                return l2;
            }
        }


}
